package com.bwda.dsrs.filecenter.controller;

import com.bwda.dsrs.base.centerbase.response.CentreCutPageResponse;
import com.bwda.dsrs.base.centerbase.response.CentreListResponse;
import com.bwda.dsrs.base.centerbase.response.ResponseEntity;
import com.bwda.dsrs.base.util.CopyUtil;
import com.bwda.dsrs.base.util.DateUtil;
import com.bwda.dsrs.base.util.StringUtil;
import com.bwda.dsrs.filecenter.domain.BusinessConstants;
import com.bwda.dsrs.filecenter.domain.condition.executionpolicy.ExecutionPolicyCondition;
import com.bwda.dsrs.filecenter.domain.exception.BusinessServiceException;
import com.bwda.dsrs.filecenter.domain.form.executionpolicy.ExecutionPolicyCreateForm;
import com.bwda.dsrs.filecenter.domain.form.executionpolicy.ExecutionPolicyQueryForm;
import com.bwda.dsrs.filecenter.domain.form.executionpolicy.ExecutionPolicyUpdateForm;
import com.bwda.dsrs.filecenter.domain.po.executionpolicy.ExecutionPolicyPo;
import com.bwda.dsrs.filecenter.domain.vo.executionpolicy.ExecutionPolicyVo;
import com.bwda.dsrs.filecenter.service.ExecutionHistoryService;
import com.bwda.dsrs.filecenter.service.ExecutionPolicyService;
import com.bwda.dsrs.filecenter.util.DateTimeUtils;
import com.bwda.dsrs.systemservice.domain.Constants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * @author Administrator
 */
@RestController
@RequestMapping("/b/executionpolicy")
@Api(value = "/b/executionpolicy", tags = "执行策略管理")
public class ExecutionPolicyController extends BaseController {

    @Autowired
    private ExecutionPolicyService executionPolicyService;

    @Autowired
    private ExecutionHistoryService executionHistoryService;


    @ApiOperation(value = "查询执行策略管理", notes = "查询执行策略管理", httpMethod = "GET")
    @RequestMapping(value = "/query", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<ExecutionPolicyVo> query(@ApiParam(value = "id", required = true) @RequestParam Integer executionPolicyId) throws BusinessServiceException {
        ExecutionPolicyPo po = executionPolicyService.queryWithValid(executionPolicyId);
        ExecutionPolicyVo vo = CopyUtil.transfer(po, ExecutionPolicyVo.class);
        return getSuccessResult(vo);
    }

    @ApiOperation(value = "查询执行策略管理数量", notes = "查询执行策略管理数量", httpMethod = "GET")
    @RequestMapping(value = "/queryCount", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<Integer> queryCount(@ModelAttribute @Valid ExecutionPolicyQueryForm form) throws BusinessServiceException {
        ExecutionPolicyCondition condition = this.getConditionByQueryForm(form);
        int count = executionPolicyService.queryCount(condition);
        return getSuccessResult(count);
    }

    @ApiOperation(value = "查询执行策略管理列表", notes = "查询执行策略管理列表", httpMethod = "GET")
    @RequestMapping(value = "/queryList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreListResponse<ExecutionPolicyVo>> queryList(@ModelAttribute @Valid ExecutionPolicyQueryForm form) throws BusinessServiceException {
        ExecutionPolicyCondition condition = this.getConditionByQueryForm(form);
        List<ExecutionPolicyPo> poList = executionPolicyService.queryList(condition);
        List<ExecutionPolicyVo> voList = CopyUtil.transfer(poList, ExecutionPolicyVo.class);
        return getSuccessResult(getListResponse(voList));
    }

    @ApiOperation(value = "查询执行策略管理列表(带分页)", notes = "查询执行策略管理列表(带分页)", httpMethod = "GET")
    @RequestMapping(value = "/queryPageList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreCutPageResponse<ExecutionPolicyVo>> queryPageList(@ModelAttribute @Valid ExecutionPolicyQueryForm form) throws BusinessServiceException {
        ExecutionPolicyCondition condition = this.getConditionByQueryForm(form);
        condition.setActiveFlag(BusinessConstants.NumberConstant.ZERO);
        List<ExecutionPolicyVo> voList = new ArrayList<>();
        int count = executionPolicyService.queryCount(condition);
        if (count > 0) {
            List<ExecutionPolicyPo> poList = executionPolicyService.queryList(condition);
            voList = CopyUtil.transfer(poList, ExecutionPolicyVo.class);
        }
        return getSuccessResult(getPageResponse(form, count, voList));
    }

    @ApiOperation(value = "新增执行策略管理", notes = "新增执行策略管理", httpMethod = "POST")
    @RequestMapping(value = "/add", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<ExecutionPolicyVo> add(@ModelAttribute @Valid ExecutionPolicyCreateForm form) throws BusinessServiceException {

        logger.info("新增执行策略任务start...form{},", form);
        String userCode = getUserCode();
        if (form == null) {
            return getFailResult("新增执行策略数据为空");
        }

        ExecutionPolicyPo po = CopyUtil.transfer(form, ExecutionPolicyPo.class);
        po.setCreateUserCode(userCode);
        po.setCreateTime(new Date());

        if (StringUtil.constainSpecialCase(po.getExecutionPolicyName())) {
            return getFailResult("任务名称包含特殊字符");
        }
        /**
         * 验证输入的策略名称是否已存在
         */
        int count = executionPolicyService.countResAuditTaskCnfgByTaskName(po);
        if (count > 0) {
            return getFailResult("此任务名称已经存在");
        }

        // 新增
        executionPolicyService.addAuditTask(po);
        ExecutionPolicyVo vo = CopyUtil.transfer(po, ExecutionPolicyVo.class);
        return getSuccessResult(vo);
    }

    @ApiOperation(value = "修改执行策略管理", notes = "修改执行策略管理", httpMethod = "POST")
    @RequestMapping(value = "/update", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity update(@ModelAttribute @Valid ExecutionPolicyUpdateForm form) throws BusinessServiceException {
        ExecutionPolicyPo po = CopyUtil.transfer(form, ExecutionPolicyPo.class);

        String userCode = getUserCode();
        po.setCreateUserCode(userCode);
        po.setCreateTime(new Date());

        //如果是定时执行判断他的时间是否在当前时间之后
        if (po != null && Constants.ResAuditCycleType.CT_TIMING.equals(po.getExecutionCycleTypeId())) {
            Date now = new Date();
            if (DateTimeUtils.compareDateTime(po.getExecutionTime(), DateUtil.formatDate(now, DateUtil.FORMAT)) == 2) {
                return getFailResult("执行时间应该大于当前时间");
            }
        }
        if (StringUtil.constainSpecialCase(po.getExecutionPolicyName())) {
            return getFailResult("任务名称包含特殊字符");
        }
        /**
         * 验证输入的策略名称是否已存在
         */
        int count = executionPolicyService.countResAuditTaskCnfgByTaskName(po);
        if (count > 0) {
            return getFailResult("此任务名称已经存在");
        }
        executionPolicyService.updateAuditTaskInfo(po);
        return getSuccessResult();
    }

    @ApiOperation(value = "删除执行策略管理", notes = "删除执行策略管理", httpMethod = "POST")
    @RequestMapping(value = "/deleteByIds", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity deleteByIds(@RequestParam Long[] executionPolicyIds) throws BusinessServiceException {

        logger.info("deleteByIds 方法，ids = {}", executionPolicyIds);
        if (executionPolicyIds == null || executionPolicyIds.length == 0) {
            return getFailResult("没有任务id");
        }

        executionPolicyService.deleteByIds(executionPolicyIds);
        return getSuccessResult();
    }


    /**
     * 启用停用任务
     *
     * @param form 策略任务对象
     * @return
     */
    @ApiOperation(value = "启用停用任务", notes = "启用停用任务", httpMethod = "POST")
    @RequestMapping(value = "/setTaskStatus", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity setTaskStatus(@ModelAttribute @Valid ExecutionPolicyUpdateForm form) {
        logger.info("启用停用任务start...");
        ExecutionPolicyPo po = CopyUtil.transfer(form, ExecutionPolicyPo.class);
        executionPolicyService.setTaskStatus(po);
        return getSuccessResult();
    }

    /**
     * 查询任务详情
     *
     * @param executionPolicyId 任务ID
     * @return
     * @throws
     */
    @ApiOperation(value = "查询策略任务详情", notes = "查询策略任务详情", httpMethod = "GET")
    @RequestMapping(value = "/queryAuditTaskInfo", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<ExecutionPolicyVo> queryAuditTaskInfo(@RequestParam Long executionPolicyId) {
        logger.info("queryAuditTaskInfo 方法，executionPolicyId = {}", executionPolicyId);
        ExecutionPolicyPo po = executionPolicyService.queryAuditTaskInfo(executionPolicyId);
        ExecutionPolicyVo vo = CopyUtil.transfer(po, ExecutionPolicyVo.class);
        return getSuccessResult(vo);
    }

    /**
     * 立即执行任务
     *
     * @param executionPolicyId 策略任务IDS
     * @return
     * @throws
     */
    @ApiOperation(value = "立即执行任务", notes = "立即执行任务", httpMethod = "GET")
    @RequestMapping(value = "/immediateExecuteTask", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity immediateExecuteTask(@RequestParam Long[] executionPolicyId) {
        logger.info("immediateExecuteTask 方法，executionPolicyId = {}", executionPolicyId);

        if (executionPolicyId == null || executionPolicyId.length == 0) {
            return getFailResult("没有任务id");
        }

        //查询是否已经有正在执行的任务
        int count = executionHistoryService.queryRuningTaskCountByTaskIds(executionPolicyId);
        if (count > 0) {
            return getFailResult("当中有正在执行的任务，请稍后操作");
        }

        executionPolicyService.immediateExecuteTask(executionPolicyId);
        return getSuccessResult();
    }


    /**
     * ExecutionPolicyQueryForm转换为ExecutionPolicyCondition
     *
     * @param form
     * @return
     */
    private ExecutionPolicyCondition getConditionByQueryForm(ExecutionPolicyQueryForm form) {
        ExecutionPolicyCondition condition = CopyUtil.transfer(form, ExecutionPolicyCondition.class);
        return condition;
    }

}